package com.bjbn.service;

import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * 航班可视化服务类
 *
 * @author bjbn
 */
@Service
public class FlightViewService {


    @Value("${external.api.token}")
    private String apiToken;


    public static WebClient createInsecureWebClient() throws SSLException {
        // 1. 配置 Netty HttpClient 忽略所有 SSL 校验  信任所有证书
        SslContext sslContext = SslContextBuilder
                .forClient()
                .protocols("TLSv1.2")
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .build();

        HttpClient httpClient = HttpClient.create()
                .secure(spec -> spec.sslContext(sslContext)).wiretap(true);

        // 2. 构建 WebClient
        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .baseUrl("https://10.126.129.199:533/restcloud/jeecg-boot")
                .build();
    }


    /**
     * 转发API请求
     *
     * @param endpoint API端点
     * @return 响应结果
     */
    public Mono<Map<String, Object>> forwardApiRequest(String endpoint) {
        try {
            WebClient webClient = createInsecureWebClient();
            return webClient.get()
                    .uri(endpoint)
                    .header("api-token", apiToken)
                    .retrieve()
                    .bodyToMono(Map.class)
                    .cast(Map.class)
                    .map(map -> (Map<String, Object>) map)
                    .onErrorResume(e -> {
                        // 记录错误日志
                        System.err.println("API转发失败: " + endpoint + ", 错误: " + e.getMessage());
                        return Mono.empty();
                    });
        } catch (Exception e) {
            return Mono.error(e);
        }
    }

    /**
     * 获取实时延误航班统计
     */
    public Mono<Map<String, Object>> getDelayStatistics() {
        return forwardApiRequest("/apvll/fltDelaySortieCount");
    }

    /**
     * 获取当前放行正常率
     */
    public Mono<Map<String, Object>> getCurrentReleaseRate() {
        return forwardApiRequest("/apvll/getCurrentReleaseRate");
    }

    /**
     * 获取今日航班、旅客量统计
     */
    public Mono<Map<String, Object>> getTodayFlightPassengerStats() {
        return forwardApiRequest("/apvll/getDayFltPsgAmount");
    }

    /**
     * 获取近一周航班靠桥率
     */
    public Mono<Map<String, Object>> getWeekCloseBridgeRate() {
        return forwardApiRequest("/apvll/getWeekCloseBridgeRate");
    }

    /**
     * 获取今年航班、旅客量统计
     */
    public Mono<Map<String, Object>> getYearFlightPassengerStats() {
        return forwardApiRequest("/apvll/getYearFltPsgAmount");
    }
} 